package liming.tool.json;

import liming.tool.file.FileRW;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class FileConfig {
    static JSONObject json = new JSONObject();
    public static void addConfig(String key, Object value){
        json.put(key,value);
    }
    public static void addConfig(JSONObject config){
        config.toMap().forEach(json::put);
    }
    public static void loader(File configFile) throws IOException {
        if(!configFile.isFile())
            throw new RuntimeException("configFile is not a file");
        String readString = FileRW.readTextFile(configFile).getContent();
        new JSONObject(readString).toMap().forEach(json::put);
    }

    public static void getConfig(ToJson toJson,String... keys){
        toJson.deserialize(getConfig(keys));
    }
    public static JSONObject getConfig(String... keys){
        new LoaderHistory(keys);
        JSONObject jsonObject = json;
        for (String key : keys) {
            jsonObject = ValueOf.valueOf(JSONObject.class,jsonObject.opt(key));
            if(jsonObject == null)
                return new JSONObject();
        }
        return new JSONObject(jsonObject.toString());
    }

    /**
     * 将以utf-8的编码格式写入文件
     * @param configFile
     * @return
     * @throws IOException
     */
    public static boolean writeHistory(File configFile) throws IOException {
        JSONObject root =  new JSONObject();
        root.put("config",json);
        root.put("history",LoaderHistory.history);
        FileRW.writeTextFile(configFile,root.toString(),false, FileRW.FileEncoding.UTF8);
        return true;
    }
    private static class LoaderHistory {
        static Set<LoaderHistory> history = new HashSet<>();
        String[] keys;

        LoaderHistory (String... keys){
            this.keys = keys;
            history.add(this);
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof LoaderHistory)) return false;
            LoaderHistory that = (LoaderHistory) o;
            return Objects.deepEquals(keys, that.keys);
        }

        @Override
        public int hashCode() {
            return Arrays.hashCode(keys);
        }
    }
}
